#include "db.h"

MYSQL *db = NULL;

void show_error(char *lable){
    printf("%s error: %s\n",lable,mysql_error(db));
}

bool connect_db(){
    mysql_library_init(0,NULL,NULL);
    db = mysql_init(NULL);
    if(mysql_real_connect(db, SERVER, DB_USER, DB_PASSWD, DB_NAME, PORT,NULL,0) !=0){
        show_error("connect");
        return false;
    }
    return true;
}

int query_db(char *sql, QUERY_Handler callback){
    if(db){
        if(!mysql_query(db, sql)){
            show_error("query");
            return 0;
        }

        MYSQL_RES *res = mysql_store_result(db);
        int rows = mysql_num_rows(res);
        int cols = mysql_num_fields(res);
        char **colnames = (char **)calloc(cols, sizeof(char *));
        int i=0;
        for(;i<cols; i++){
            colnames[i] = (char *)calloc(1, 32);
            MYSQL_FIELD *f = mysql_fetch_field(res);
            strncpy(colnames[i],  f->name, strlen(f->name));
        }
        for(i=0;i<rows;i++){
            MYSQL_ROW rowdata = mysql_fetch_row(res);
            callback(colnames, rowdata);
        }

        for(i=0;i<cols;i++){
            free(colnames[i]);
        }
        free(colnames);
        return rows;
    }
    return 0;
}

int insert_db(char *sql){
    int res=0;
    if(db){
        if(!mysql_real_query(db, sql, strlen(sql))){
            show_error("insert");
            return res;
        }

        res = mysql_affected_rows(db);  // 执行dml语句后，获取影响的行数据
    }
    return res;
}
int update_db(char *sql){
    int res=0;
    if(db){
        if(!mysql_real_query(db, sql, strlen(sql))){
            show_error("update");
            return res;
        }

        res = mysql_affected_rows(db);  // 执行dml语句后，获取影响的行数据
    }
    return res;
}
int delete_db(char *table, char *pk_column, char *pk_value){
    char sql[256]="";
    sprintf("delete from %s where %s='%s'", table, pk_column, pk_value);
    int res=0;
    if(db){
        if(!mysql_real_query(db, sql, strlen(sql))){
            show_error("update");
            return res;
        }

        res = mysql_affected_rows(db);  // 执行dml语句后，获取影响的行数据
    }
    return res;
}
void close_db(){
    if(db){
        mysql_close(db);
    }
    mysql_library_end();
}
